package com.bilibili.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bilibili.entity.CommenResult;
import com.bilibili.entity.User;
import com.bilibili.entity.Video;
import com.bilibili.service.VideoService;
import com.bilibili.service.impl.VideoServiceImpl;

/**
 * Servlet implementation class VideoServlet
 */
@WebServlet("/video.do")
public class VideoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public VideoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json;charset=UTF-8");
		// 获取请求参数中的 videoId
		String videoIdStr = request.getParameter("videoId");
		if (videoIdStr != null && !videoIdStr.isEmpty()) {
			try {
				int videoId = Integer.parseInt(videoIdStr);
				// 调用 VideoService 获取视频信息
				VideoService vs = new VideoServiceImpl();
				int user_id = ((User)request.getSession().getAttribute("loginUser")).getUserId();
				List<Video> videoList = vs.selectByAll(user_id);
				System.out.println(videoList.get(0).getTitle());
				CommenResult result = new CommenResult();
				if (videoList.size() > 0) {
					// 将视频标题作为数据返回
					result.setData(videoList);
				} else {
					result.setData("未知视频标题");
				}
				response.getWriter().write(result.toJOSNString());
			} catch (NumberFormatException e) {
				e.printStackTrace();
				response.getWriter().write("{\"data\": \"无效的视频 ID\"}");
			}
		} else {
			response.getWriter().write("{\"data\": \"未提供视频 ID\"}");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 这里简单地调用 doGet 方法，也可以根据需求单独处理 POST 请求
		doGet(request, response);
	}

}